﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Authentication;
using System.Web;
using AutoPartsSearch.Domain.Abstract;
using AutoPartsSearch.Domain.Abstract.Repositories;
using System.Security.Principal;
using AutoPartsSearch.Domain.Entities;
using AutoPartsSearch.Domain.Exceptions;

namespace AutoPartsSearch.Web.Infrastructure.Concrete
{
    public class SellerGetter : ISellerGetter
    {
        private ISellerRepository _sellerRepository;

        public SellerGetter(ISellerRepository sellerRepository)
        {
            this._sellerRepository = sellerRepository;
        }

        public int GetCurrentSellerId(IPrincipal user)
        {
            if (!user.Identity.IsAuthenticated)
            {
                throw new AuthenticationException("Seller must be authenticated.");
            }
            var seller = this._sellerRepository.GetByCompanyName(user.Identity.Name);
            if (seller == null)
            {
                throw new SellerNotFoundException(string.Format("Seller '{0}' not found.", user.Identity.Name));
            }
            return seller.Id;
        }

        public Seller GetSellerByUser(IPrincipal user)
        {
            var seller = this._sellerRepository.GetByCompanyName(user.Identity.Name);
            if (seller == null)
            {
                throw new SellerNotFoundException(string.Format("Seller '{0}' not found.", user.Identity.Name));
            }
            return seller;
        }
    }
}